package com.zj.core.activity

import android.os.Bundle
import android.view.View
import com.dialogutils.DialogUtils
import com.zj.core.base.BaseApplication
import com.zj.core.net.NetPresenter
import com.utils.DateUtils
import com.dialogutils.ToastUtil
import com.fileutils.NumberUtils
import com.quitutils.SwipeBackLayout
import com.zj.core.R
import com.zj.core.base.BaseVoiceActivity
import com.zj.core.bean.VoiceTemplateBean
import com.zj.core.dialog.TemplateDialog
import com.zj.core.dialog.TemplateListDialog
import com.zj.core.interfaces.TextMessageIml
import com.zj.core.interfaces.TemplateTitleIml
import com.zj.core.net.NetValueCallBackIml
import com.zj.core.tools.Constant
import com.zj.core.tools.VoiceFormatTools


/**
 * 日期：2019年6月22日
 * 公司：北京子杰宝贝科技有限公司
 * 地址：北京市朝阳区朝阳农场
 * 开发者：达选文
 * <p>
 * 主体功能：数据录入功能
 */
class RecordActivity : BaseVoiceActivity() {

    /**
     * 防止重复提交
     */
    companion object {
        var commitStatu: Boolean? = true
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setQuitMode(SwipeBackLayout.EDGE_LEFT)
    }

    /**
     * 如果非首行，判断是否是模板
     */
    override fun isTemplate(mes: String) {
        NetPresenter().getVoiceTemplate(
            templateIml,
            mes,
            mHospitalID,
            mDepartmentID
        )
    }

    /**
     * 模板清单
     */
    override fun templateList() {
        TemplateListDialog(this@RecordActivity, mHospitalID, mDepartmentID, mTitleArr)
            .setTemplateListener(templateValueIml)
            .show()
    }

    /**
     * 模板清单数据返回
     */
    private var templateValueIml=object: TextMessageIml {
        override fun messageResult(value: String){
            ArrayList<String>().let {
                it.add("模板")
                it.add(value)
                changeDialog(0, it)
            }
        }
    }

    /**
     * 语音正常录入
     */
    override fun normalInput(formatValue: String) {
        if (mHospitalStatuStr != "" && mFormListStr != "") {
            cleanPatternArr()
            timeCheck(formatValue)
        } else {
            ToastUtil.showShort(BaseApplication.context, "关键字列表获取失败")
        }
    }

    /**
     * 时间判断
     */
    private fun timeCheck(mes: String) {
        val formatData = DateUtils.dateFormat(0,mes,mFormListStr)
        if (formatData != "" && DateUtils.isValidDate(formatData, "HH:mm")) {
            val timeValue = formatData.split("|")

            //如果第二行是模板关键字
            if (timeValue.size == 2 && timeValue[1] != "" && templateContains(timeValue[1])) {
                addTimeValue(checkHospitalStatus(timeValue[0]))
                notifyDataChange()

                NetPresenter().getVoiceTemplate(
                    templateIml,
                    timeValue[1],
                    mHospitalID,
                    mDepartmentID
                )
            } else if (timeValue.size == 2 && timeValue[1] != "" && timeValue[1].contains("模板") && !templateContains(timeValue[1])){
                ToastUtil.showShort(BaseApplication.context, "未找到${timeValue[1]}")
            } else if (timeValue.size == 1 && timeValue[0] != "") {
                addTimeValue(checkHospitalStatus(timeValue[0]))
                notifyDataChange()
            } else if (timeValue.size == 2 && timeValue[0] != "") {
                addTimeValue(checkHospitalStatus(timeValue[0]))
                patternNomalVoice(timeValue[1])
            }
        } else if (mes.contains("模板") && !templateContains(mes)) {
            ToastUtil.showShort(BaseApplication.context, "未找到$mes")
        } else {
            patternNomalVoice(mes)
        }
        scrollToIndex()
    }

    /**
     * 模板数据回调
     *
     * @param rowsBean
     */
    private val templateIml = object : NetValueCallBackIml {
        override fun onNext(values: Any?, bean: Any?) {
            if ((values as ArrayList<VoiceTemplateBean.VoiceWordBean.DatEntity.RowsEntity>).size != 0) {
                dialogShow(values, bean as String)
            } else {
                ToastUtil.showShort(BaseApplication.context, "未获取到$bean")
            }
        }

        override fun onError() {
            ToastUtil.showShort(BaseApplication.context, "模板数据获取失败")
        }

        override fun onSubscribe(data: Any?) {}
        override fun onComplete() {}
    }

    /**
     *    模板弹窗类型
     *    mDialogType
     * 0：模板内容填空、获取内容值
     * 1：获取模板内容对应的序列值
     */
    private fun dialogShow(
        values: ArrayList<VoiceTemplateBean.VoiceWordBean.DatEntity.RowsEntity>,
        templateName: String
    ) {
        TemplateDialog(this@RecordActivity, mDialogType).let {
            it.setItemBean(values)
            it.setDialogTitle(templateName)
            it.setCallBackIml(mTitleIml)
            it.show()
        }
    }

    /**
     * 模板内容选择后回调
     *
     * @param titleArr
     */
    private val mTitleIml = object : TemplateTitleIml {
        override fun callBackTitle(titleArr: String, titleName: String) {
            ArrayList<String>().let {
                it.add(titleName)
                it.add(titleArr)
                changeDialog(0, it)
            }
        }
    }

    /**
     * 模板修改
     */
    override fun templateStatus(name: String, form: String, index: Int) {
        checkAddData(name, form)
        notifyDataChange()
        scrollToIndex()
    }

    /**
     * 提交数据
     */
    override fun commitInputValue() {
        val mListValue = getAllListValue()
        when {
            mListValue[0][1] == "" -> ToastUtil.showShort(BaseApplication.context, "请先录入时间项")
            mListValue[1][1] == "" -> ToastUtil.showShort(BaseApplication.context, "请选择表单后提交")
            mListValue.size <= 2 -> ToastUtil.showShort(BaseApplication.context, "请录入数据后提交")
            else -> DialogUtils.create(
                this, null, "是否提交数据？", "提交",
                commitListener, "取消", commitListener, true, true,
                false
            ).show()
        }
    }

    private var commitListener: View.OnClickListener = View.OnClickListener { v ->
        var mTemplateStr = ""           //模板
        var mFormStr = ""               //表单
        var mCommonStr = ""
        var mTimeStr = ""               //时间项
        var mChTimeStr = ""             //中文时间
        var mHosStr = ""                //住院状态

        var mTimeStatus = false        //时间项是否存在
        var mHosStatus = false         //住院状态是否存在

        when (v.id) {
            R.id.common_dialog_cancel_tv -> {
            }

            R.id.common_dialog_confirm_tv -> {
                commitStatu = false
                mHospitalStatuStr
                getAllListValue().let {
                    for (itemValue in 0 until it.size) {
                        if (itemValue == 1 && it[itemValue][0] == "表单") {
                            mFormStr = it[itemValue][1]
                        }else if (it[itemValue][0].contains("模板")) {
                            mTemplateStr = if (mTemplateStr == "") {
                                it[itemValue][1]
                            } else {
                                mTemplateStr + "\n" + it[itemValue][1]
                            }
                        } else if (it[itemValue][0] == "时间"){
                            mTimeStr = it[itemValue][1]
                            mTimeStatus = true
                            if (mHosStatus){
                                if (mStatuMap?.get(mHosStr) == "1"){
                                    mChTimeStr=mTimeStr
                                }
                            }
                        } else if (it[itemValue][0] == "状态") {
                            mHosStr = it[itemValue][1]
                            mCommonStr = mCommonStr + ",状态|" + it[itemValue][1]
                            mHosStatus = true
                            if (mTimeStatus){
                                if (mStatuMap?.get(mHosStr) == "1"){
                                    mChTimeStr=mTimeStr
                                }
                            }
                        } else {
                            mCommonStr = if (mCommonStr == "") {
                                it[itemValue][0] + "|" + it[itemValue][1]
                            } else {
                                mCommonStr + "," + it[itemValue][0] + "|" + it[itemValue][1]
                            }
                        }
                    }
                }

                mCommonStr = if(mChTimeStr!=""){
                    "$mCommonStr,时间|${DateUtils.dateFormat(0,NumberUtils.CharDateFormat(mTimeStr),"").split("|")[0]}"
                }else{
                    "$mCommonStr,时间|$mTimeStr"
                }

                NetPresenter().postVoiceHistory(
                    object : NetValueCallBackIml {
                        override fun onNext(values: Any?, bean: Any?) {
                            commitStatu = true
                            saveDialog = 1
                            ToastUtil.showShort(BaseApplication.context, "提交成功")
                            cacheInputData("")
                            setResult(Constant.RESULT_RECORD_SKY)
                            finish()
                        }

                        override fun onComplete() {}
                        override fun onSubscribe(data: Any?) {}
                        override fun onError() {
                            commitStatu = true
                            ToastUtil.showShort(BaseApplication.context, "提交失败")
                        }
                    },
                    mRecordStatus,
                    mHospitalID,
                    mDepartmentID,
                    mRecordBean?.patientid,
                    mRecordBean?.nurseid,
                    mCommonStr,
                    VoiceFormatTools.wipeBracketOnCommitValue(mTemplateStr),
                    mFormStr,
                    mChTimeStr
                )
            }
        }
    }

    /**
     * 滑动退出
     * 保存数据
     */
    override fun finish(){
        if (saveDialog == 0) {
            val list = getAllListValue()
            if (list.size > 0){
                if((list.size==2)&&(list[0][0]=="时间")&&(list[1][0]=="表单")){
                    if((list[0][1]=="")&&(list[1][1]=="")){
                        cacheInputData("")
                    }else{
                        cacheInputData(mGson?.toJson(list)!!)
                    }
                }else{
                    cacheInputData(mGson?.toJson(list)!!)
                }
            } else {
                cacheInputData("")
            }
            setResult(Constant.RESULT_RECORD_SKY)
        }
        super.finish()
    }
}